const db = require('./config/connect')
const express = require('express')
const app = express()
const ejs = require('ejs')
const path = require('path')
const {Order}= require('./schema/orderSchema')
const moment=require('moment')
// 连接数据库
db(()=>{

    app.use(express.urlencoded())
    app.set('view engine','ejs')
    app.set('views',path.resolve(__dirname,'./views'))
    app.use(express.static(path.resolve(__dirname,'./assets')))
    // 设置静态资源
    app.get('/',(req,res)=>{
        res.render('index')
    })
    app.get('/list',(req,res)=>{
        res.setHeader('content-type','text/html;charset=utf-8')
        
        Order.find({isHidden:false}).then(list=>{
            res.setCode= 200;
            res.render('list', {list:list, moment:moment, count:list.length})
        },e=>{
            res.setCode = 200;
            res.send('获取数据失败')
        })
    })
    app.get('/list/:type',(req,res)=>{
        console.log(req.params.type)
        // Order.find({type:req.params.type}).limit(3).then(data=>{
        Order.find({type:req.params.type, isHidden:false}).then(data=>{
            if(data){
                res.render('list',{list:data,moment:moment,count:data.length})
            }else{
                res.send("筛选出错请<a href='/list'>返回列表</a>")
            }
        })
        
    })
    app.get('/delOrder/:id',(req,res)=>{
        let id = req.params.id;
        let a = Order.findOne({_id:id});
        a.then(async data=>{
            if(data){
                Order.updateOne({_id:id},{isHidden:true}).then((data)=>{
                    res.send('删除成功请<a href="/list">返回列表</a>')
                },err=>{
                    res.send('删除失败，请<a href="/list">返回列表</a>')
                })
            }else{
                res.send('未查找到数据，请<a href="/list">返回列表</a>')
            }
        },err=>{
            res.send('未查找到数据，请<a href="/list">返回列表</a>')            
        })
    })

    let routers = express.Router()
    routers.post('/addOrder',(req,res)=>{
        console.log(req.body,'===ff')
        let s = new Order(req.body)
        
        s.save().then(result=>{
            res.render('submitStatus',{success:1,direction:'提交成功'})
        },e=>{
            console.log('---2')
            res.render('submitStatus',{success:0,direction:'提交失败'})
        })
    })
    
    app.use('/admin',routers)
    // 监听端口
    app.listen('3000')
})
